package com.dgut.forum.controller;


import com.dgut.forum.common.AppResult;
import com.dgut.forum.common.ResultCode;
import com.dgut.forum.config.AppConfig;
import com.dgut.forum.dao.BoardMapper;
import com.dgut.forum.exception.ApplicationException;
import com.dgut.forum.model.Article;
import com.dgut.forum.model.ArticleReply;
import com.dgut.forum.model.Board;
import com.dgut.forum.model.User;
import com.dgut.forum.services.impl.ArticleServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.yaml.snakeyaml.events.Event;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Api(tags = "文章接口")
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleServiceImpl articleService;
    @Autowired
    private BoardMapper boardMapper;

    @ApiOperation("新建文章")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("版块id") @RequestParam("boardId") @NonNull Long boardId,
                            @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("文章正文") @RequestParam("content") @NonNull String content){

        //校验用户被禁言
        HttpSession session=request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1){
            log.info("用户被禁言 用户id="+user.getId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED_STATE));
        }
        //校验版块是否存在
        Board board=boardMapper.selectByPrimaryKey(boardId);
        if(board==null){
            log.info("该板块不存在 board id="+boardId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        if(board.getState()==1){
            log.info("版块被禁言 版块id="+board.getId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_BANNED_PUBLIC));
        }
        //封装文章对象
        Article article=new Article();
        article.setUserId(user.getId());
        article.setBoardId(boardId);
        article.setTitle(title);
        article.setContent(content);
        articleService.create(article);

        return AppResult.success();
    }

    @ApiOperation("获取板块文章")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam("版块id") @RequestParam(value = "boardId",required = false) Long boardId){
        List<Article> articles;
        if(boardId==null){
            articles=articleService.selectAll();
        }else{
            //检查版块Id合法性
            if(boardId<0){
                log.info("版块Id不合法"+ResultCode.FAILED_PARAMS_VALIDATE.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            }
            //校验版块是否存在
            Board board=boardMapper.selectByPrimaryKey(boardId);
            if(board==null){
                log.info("该板块不存在 board id="+boardId);
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
            }
            articles=articleService.selectAllByBoardId(boardId);
        }

        if(articles.isEmpty()){
            log.info("版块中文章数为0");
            articles=new ArrayList<>();
        }
        return AppResult.success(articles);
    }

    @ApiOperation("获取板块文章")
    @GetMapping("/getDetailById")
    public AppResult<Article> getDetailById(@ApiParam("帖子id") @RequestParam(value = "Id") Long Id){
        Article article;

        //检查版块Id合法性
        if(Id<0){
            log.info("文章Id不合法"+ResultCode.FAILED_PARAMS_VALIDATE);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        article=articleService.selectDetailById(Id);

        if(article==null){
            log.warn("查询文章详情失败，文章id="+Id+"，文章不存在");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        return AppResult.success(article);
    }

    @GetMapping("/details")
    public AppResult<Article> Detail(HttpServletRequest request,@ApiParam("帖子id") @RequestParam("Id") @NonNull Long Id){
        HttpSession session=request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);

        Article article=articleService.selectDetailById(Id);
        //判断文章是否存在
        if(article==null){
            log.warn("查询文章详情失败，文章id="+Id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if(user.getId()==article.getUserId()){
            article.setOWn(true);
        }
        return AppResult.success(article);
    }

    @ApiOperation("修改帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("帖子id") @RequestParam("Id") @NonNull Long Id,
                            @ApiParam("帖子id") @RequestParam("title") @NonNull String title,
                            @ApiParam("帖子id") @RequestParam("content") @NonNull String content){
        HttpSession session= request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);

        Article article=articleService.selectById(Id);
        //判断文章是否存在
        if(article==null){
            log.warn("查询文章详情失败，文章id="+Id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //判断发起修改的人是否为作者
        if(article.getUserId()!=user.getId()){
            log.warn("用户没有权限修改文章,article id="+Id+",用户Id="+user.getId()+",作者Id="+article.getUserId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_HAVE_NOT_PERMISSION));
        }
        //判断作者是否能够发言
        if(user.getState()==1){
            log.warn("用户被禁言,用户Id="+user.getId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED_STATE));
        }
        //判断帖子是否能被修改
        if(article.getState()==1||article.getDeleteState()==1){
            log.warn("该帖子状态异常,不允许修改");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED_STATE));
        }
        articleService.modify(Id,title,content);
        log.info("修改帖子成功");
        return AppResult.success();
    }

    @ApiOperation("点赞帖子")
    @GetMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,
                              @ApiParam("帖子id") @RequestParam("Id") @NonNull Long Id){
        //判断用户是否被禁言
        //被禁言用户只能看
        HttpSession session=request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);

        if(user.getState()==1){
            log.warn("用户被禁言,不允许点赞,用户Id="+user.getId()+",帖子Id="+Id);
            return AppResult.failed(ResultCode.FAILED_USER_BANNED_STATE);
        }
        Article article=articleService.selectById(Id);
        if(article==null||article.getDeleteState()==1){
            log.warn("帖子不存在或者已经被删除,帖子Id="+ Id);
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        articleService.thumbsUpById(Id);
        return AppResult.success();
    }

    @ApiOperation("删除帖子")
    @GetMapping("/delete")
    public AppResult delete(HttpServletRequest request,
                            @ApiParam("帖子id") @RequestParam("Id") @NonNull Long Id){
        HttpSession session=request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1){
            log.warn("用户被禁言");
            return AppResult.failed(ResultCode.FAILED_USER_BANNED_STATE);
        }
        Article article=articleService.selectById(Id);
        if(article==null){
            log.warn("删除帖子时,帖子不存在");
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if(article.getUserId()!=user.getId()){
            log.warn("没有权限删除该帖子");
            return AppResult.failed(ResultCode.FAILED_USER_HAVE_NOT_PERMISSION);
        }
        articleService.delete(Id);
        return AppResult.success();
    }

    /*
     * 根据用户Id查询用户的所有文章,用户主页展示
     *
     * */
    @ApiOperation("获取用户所有帖子")
    @GetMapping("/getUserAllArticles")
    public AppResult<List<Article>> getUserAllArticles(HttpServletRequest request,
                                                            @ApiParam("用户id") @RequestParam(value = "userId",required = false)Long userId){
        if(userId==null){
            HttpSession session=request.getSession(false);
            User user= (User) session.getAttribute(AppConfig.USER_SESSION);
            userId=user.getId();
        }
        List<Article> ret=articleService.selectAllByUserId(userId);
        return AppResult.success(ret);
    }
}
